#include "sonic.h"
#include <intrins.h>


void Delay12us(void)	//@12.000MHz
{
	unsigned char data i;

	_nop_();
	_nop_();
	i = 33;
	while (--i);
}

void sonic_init() {
	uchar i;
	
	for(i=0; i<8; i++) {
		TX = 1;
		Delay12us();
		TX = 0;
		Delay12us();
	}
}



uchar sonic_read() {
	uint time;
	
	TMOD &= 0xF0;
	TH0 = TL0 = 0;
	
	sonic_init();
	TR0 = 1;
	
	while(RX && !TF0);
	
	TR0 = 0;
	if(!TF0) {
		time = ((TH0 << 8) | TL0);
		return (time*0.017);
	} else {
		TF0 = 0;
		return 255;
	}
	
}

